package cn.smbms.controller;

import cn.smbms.pojo.Role;
import cn.smbms.pojo.User;
import cn.smbms.service.RoleService;
import cn.smbms.service.UserService;
import cn.smbms.util.Constants;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Classname UserController
 * @Description TODO
 * @Date 2020-10-09 15:50
 * @Created by 26440
 */
@Controller
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    /**
     * 登入系统
     *
     * @param userCode
     * @param userPassword
     * @param request
     * @return
     */
    @RequestMapping("/login.html")
    public String test(@RequestParam(name = "userCode") String userCode,
                       @RequestParam(name = "userPassword") String userPassword,
                       HttpServletRequest request) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<User>();
        queryWrapper.eq("userCode", userCode);
        User user = userService.getOne(queryWrapper);
        String error = "";
        if (user == null) {
            error = "用户名不存在";
        } else if (!user.getUserPassword().equals(userPassword)) {
            error = "用户名或密码输入错误";
        } else {
            //登入成功
            request.getSession().setAttribute(Constants.USER_SESSION, user);
            return "frame";
        }
        request.setAttribute("error", error);
        return "forward:login.jsp";
        //throw new RuntimeException("出现异常");
    }

    /**
     * 退出系统
     *
     * @param session
     * @return
     */
    @RequestMapping("/logout.html")
    public String logout(HttpSession session) {
        session.invalidate();
        return "redirect:logout.html";
    }

    @RequestMapping("/userlist.html")
    public String userList(String queryName,
                           Integer queryUserRole,
                           @RequestParam(defaultValue = "1") Integer pageIndex,
                           HttpServletRequest request) {

        QueryWrapper<User> wrapper = new QueryWrapper<User>();
        wrapper.like(!StringUtils.isEmpty(queryName), "userName", queryName);
        wrapper.eq(queryUserRole != null && queryUserRole != 0, "userRole", queryUserRole);

        List<Role> roleList = roleService.list();
        //实现分页每页⑧条
        PageHelper.startPage(pageIndex, 8);
        List<User> userList = this.userService.getUserService(wrapper);
        PageInfo<User> pi = new PageInfo<User>(userList);
        request.setAttribute("totalPageCount", pi.getPages());
        request.setAttribute("totalCount", pi.getTotal());
        request.setAttribute("currentPageNo", pi.getPageNum());

        request.setAttribute("roleList", roleList);
        request.setAttribute("userList", userList);

        request.setAttribute("queryUserName", queryName);
        request.setAttribute("queryUserRole", queryUserRole);
        return "userlist";
    }

    /*//局部异常
    @ExceptionHandler(RuntimeException.class)
    public String exceptionHandler(RuntimeException e, HttpServletRequest request) {
        //请异常存储到请求中
        request.setAttribute("exception", e);
        return "error";
    }*/

    /**
     * 添加用户功能
     *
     * @return
     */
    @RequestMapping("/useradd.html")
    public String userAdd(HttpServletRequest request) {
        List<Role> roleList = roleService.list();
        request.setAttribute("roleList", roleList);
        return "useradd";
    }

    @RequestMapping("/usersave.do")
    public String save(@Valid User user, HttpServletRequest request) {
        User oldUser = (User) request.getSession().getAttribute(Constants.USER_SESSION);
        user.setCreatedBy(oldUser.getId());
        user.setCreationDate(new Date());
       /* user.setCreatedBy("");
        user.setCreationDate("");*/
        if (userService.save(user)) {
            return "redirect:userlist.html";
        }
        return "redirect:useradd.jsp";
    }

    /**
     * 修改
     *
     * @param uid
     * @param request
     * @return
     */
    @RequestMapping("/usermodify.html")
    public String update(Integer uid, HttpServletRequest request) {
        User user = userService.getById(uid);
        request.setAttribute("user", user);
        return "usermodify";
    }

    @RequestMapping(value = "getroleList", method = RequestMethod.GET,
            produces = "application/json;charset-utf8")
    @ResponseBody
    public Object getRoleList() {
        List<Role> roleList = roleService.list();

        return roleList;
    }

    @RequestMapping("/userUpdate.html")
    public String userUpdate(User user, HttpServletRequest request) {
        //拿到登入的id
        User oldUser = (User) request.getSession().getAttribute(Constants.USER_SESSION);
        System.out.println(user);
        user.setModifyBy(oldUser.getId());
        user.setModifyDate(new Date());
        if (userService.updateById(user)) {
            return "redirect:userlist.html";
        }
        return "redirect:usermodify.html?uid=" + user.getId();
    }

    /**
     * 删除
     * @param uid
     * @return
     */
    @RequestMapping("userdelete.json")
    @ResponseBody
    public Object userDelete(Integer uid) {
        Map<String, Object> map = new HashMap<String, Object>();
        if (userService.removeById(uid)) {
            map.put("delResult", "true");
        } else {
            map.put("delResult", "false");
        }
        return map;
    }

    /**
     * 查看某用户信息
     *
     * @param uid
     * @param request
     * @return
     */
    @RequestMapping("userview.html/{id}")
    public String userView(@PathVariable("id") Integer uid, HttpServletRequest request) {
        User user = userService.getUserService(new QueryWrapper<User>().
                eq("u.id", uid)).get(0);
        request.setAttribute("user", user);
        return "userview";
    }

    @RequestMapping("/ucexist.json/{userCode}")
    @ResponseBody
    public Object ucexist(@PathVariable("userCode") String userCode) {
        System.out.println(userCode);
        Map<String, Object> map = new HashMap<String, Object>();
        User user = userService.getOne(new QueryWrapper<User>().eq("userCode", userCode));
        if (user == null) {
            map.put("userCode", "noExist");
        } else {
            map.put("userCode", "exist");
        }
        return map;
    }

    @RequestMapping("pwdmodify")
    public String pwdModify() {
        return "pwdmodify";
    }

    @RequestMapping("/pwdcheck/{oldpassword}")
    @ResponseBody
    public Object pwdCheck(@PathVariable("oldpassword") String oldpassword,
                           HttpSession session) {
        Map<String, Object> map = new HashMap<String, Object>();
        User LoginUser = (User) session.getAttribute(Constants.USER_SESSION);

        if (LoginUser == null) {
            //session过期了
            map.put("result", "sessionerror");
        } else if (!LoginUser.getUserPassword().equals(oldpassword)) {
            //旧密码输入错误
            map.put("result", "false");
        } else {
            //输入正确
            map.put("result", "true");
        }
        return map;
    }

    @RequestMapping("pwdupdate")
    public String pwdupdate(String newpassword,HttpSession session) {
        User LoginUser = (User) session.getAttribute(Constants.USER_SESSION);
        LoginUser.setUserPassword(newpassword);
        if(userService.update(new UpdateWrapper<User>().eq("id",LoginUser.getId())
                .set("userPassword",newpassword))){
            //修改成功
            return "redirect:login.jsp";

        }else {
            return "pwdmofigy";
        }
    }
}